package com.jingdianjichi.subject.application.interceptor;

import com.jingdianjichi.subject.common.utils.LoginUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ThreadUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * feign的请求拦截器,两个微服务之间去调用的时候,我们MVC拦截到的是,无法传递过去的,我们通过Feign调用的时候要重新放一遍的,这auth服务才能拦截到的
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    private static final String LOGIN_ID="loginId";


    @Override
    public void apply(RequestTemplate requestTemplate) {
        //RequestContextHolder 是 Spring 提供的工具类，用来获取当前线程的请求上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        if(Objects.nonNull(request)){
            String loginId = request.getHeader(LOGIN_ID);      //这里使用TheadLocal也是可以的
            if (StringUtils.isNotBlank(loginId)){
                requestTemplate.header(LOGIN_ID,loginId);
            }
        }

    }

    /*
        //ThreadLocal版本
        @Override
        public void apply(RequestTemplate requestTemplate) {
            String loginId = LoginUtil.getLoginId();

            if(StringUtils.isNotBlank(loginId)){
                if (StringUtils.isNotBlank(loginId)){
                    requestTemplate.header(LOGIN_ID,loginId);
                }
            }

        }
     */
}
